package com.leetcode.p0;

import com.bean.ListNode;
import com.utils.DataUtils;

public class Test2_2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listHead = new ListNode();
        ListNode cur = listHead;

        int carry = 0;

        while (l1 != null || l2 != null || carry != 0) {
            int data1 = l1 != null ? l1.val : 0;
            int data2 = l2 != null ? l2.val : 0;

            int sum = data1 + data2 + carry;

            if (sum >= 10) {
                carry = 1;
            } else {
                carry = 0;
            }

            cur.next = new ListNode(sum % 10);
            cur = cur.next;


            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }
        }

        return listHead.next;
    }

    public static void main(String[] args) {
        Test2_2 test = new Test2_2();
        ListNode l1 = DataUtils.getListNode(new int[]{1, 4, 5});
        ListNode l2 = DataUtils.getListNode(new int[]{4, 4, 5, 9});
        ListNode result = test.addTwoNumbers(l1, l2);
        DataUtils.printListNode(result);
    }
}
